#!/usr/bin/python
# -*- coding: utf-8 -*-

"""

"""

import sys
import os
import radio_config
import radio_base
import datetime
import time

def exit(msg):
    sys.stderr.write(msg + "\n")
    sys.stderr.write("Usage: radio_archive.py BROADCASTNAME DATE [description]\n")
    sys.exit(0)

def main(broadcastname, date_, descr=""):

    broadcasts = [s for s in radio_config.broadcasts if s[0] == broadcastname]
    
    try:
        date_ = datetime.datetime(*time.strptime(date_, radio_config.dateformat)[0:6])
    except (ValueError, IndexError):
        exit("Date '%s' can not be interpreted using format '%s'." % (date_,
                                                                     radio_config.dateformat))

    if (datetime.datetime.today() - date_).days > 7:
        exit(u"Broadcast from '%s' not available anymore (older than 1 week)" % date_)

    weekday = radio_config.weekdays[date_.weekday()]
    broadcasts = [s for s in broadcasts if s[1] == weekday]
    
    if len(broadcasts) > 1:
        exit("Broadcastname '%s' and weekday '%s' not unique in configutation: " \
             "(%s)\n" % (broadcastname, weekday, broadcasts))

    try:
        broadcast = broadcasts[0]
    except IndexError:
        exit("No broadcast '%s' found for date '%s' and weekday '%s'.\n" \
             % (broadcastname, date_, weekday))

    if broadcast[3] == "24:00":
        date_ = date_ + datetime.timedelta(days=1)
        time_ = "00:00"
    else:
        time_ = broadcast[3]

    isodate = date_.strftime("%Y-%m-%d")
    date_ = datetime.datetime(date_.year, date_.month, date_.day, \
                              int(time_.split(":")[0]),
                              int(time_.split(":")[1])) + \
                              datetime.timedelta(minutes=radio_config.overflow_time + 1)

    if descr: descr = "_" + descr

    dir_ = radio_config.dir_

    cmd = "cp %(dir_)s/%(weekday)s/%(broadcastname)s.ogg %(dir_)s/archiv/" \
          "%(broadcastname)s_%(isodate)s%(descr)s.ogg" % locals()

    if date_ >= datetime.datetime.today():
        cmd = "echo '%s' | at %02d:%02d %s" % (cmd, date_.hour, date_.minute,
                                               date_.strftime("%d.%m.%y"))
    return cmd

if __name__ == "__main__":
    os.system(main(*sys.argv[1:]))


